<?php
/*
Plugin Name: Import Excel To Tag
Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
Description: A brief description of the Plugin.
Version: 1.0
Author: Administrator
Author URI: http://URI_Of_The_Plugin_Author
License: A "Slug" license name e.g. GPL2
*/

if (!defined('ABSPATH')) {
    die();
}



class import_excel{

    public $settings = [
        'access_level' => 'administrator'
    ];

    public $error = false;


    public function admin_page(){
        $view_name = 'import';

        if ( isset( $_REQUEST['action'] ) && in_array($_REQUEST['action'],['import']) ) {
            $view_name = $_REQUEST['action'];
        }

        //文件对应的标签的值
        $type = 'tag';
        switch($view_name){
            case "import":
                //uploading file
                if(isset($_FILES['uploadedfile'])){
                    $file_info = pathinfo($_FILES['uploadedfile']['name']);
                    if($file_info['extension'] != 'csv'){
                        $this->error = "请上传csv的文件,可用把Excel另存为csv文件";
                        return $this->view($view_name);
                    }
                }

                $this->view($view_name);

                //导入
                if(isset($_FILES['uploadedfile'])){
                    $this->import($type,$file_info['extensionl'],$_FILES['uploadedfile']['tmp_name']);
                }

                break;
        }

        return true;

    }

    /**
     * 导入
     * @param $type 导入类型
     * @params $file_object
     */
    public function import($type,$file_type,$file_path){
        $this->log_begin();
        switch($type){
               case 'tag':
                   //打开文件句柄
                   if(!$FS = fopen($file_path,"r")){
                        return $this->log("打开文件失败");
                   }


                   setlocale(LC_ALL, 'zh_CN'); //设置地区信息（地域信息）
                   //打开cvs
                   set_time_limit(300);
                   while ($data = fgetcsv($FS, 1000, ",")) {
                       if(isset($data[0]) && !empty($data[0])){
                           $tag = $data[0];
                           $file_encoding = mb_detect_encoding($tag,array("EUC-CN","ASCII","UTF-8","GB2312","GBK","BIG5"));
                           if(!$file_encoding){
                               return $this->log("无法识别文件编码");
                           }
                           //$this->log("文件编码类型是:".$file_encoding);
                           if($file_encoding != 'UTF-8'){
                               $tag = mb_convert_encoding($tag,"UTF-8",$file_encoding);
                           }

                           if(!$parent_term = term_exists( $tag, 'post_tag' )){
                               $isError = wp_insert_term(
                                    $tag, // the term
                                   'post_tag'// the taxonom
                               );
                               if ( is_wp_error($isError) ){
                                   $this->log("标签(".$tag.")添加<span style='color:red;'>失败</span>,原因:".$isError->get_error_message());
                               }else{
                                   $this->log("标签(".$tag.")添加成功");
                               }
                           }
                       }
                   }
                   $this->log("导入完成!");
                   break;
            }

        $this->log_end();
    }

    public function log_begin(){
        echo '<div  class=" import_log">';
    }

    public function log_end(){
        echo '</div>';
    }
    /**
     * 日志
     * @param $string
     */
    public function log($string){
        echo "<p>".$string."</p>";
        flush();
    }

    /**
     * 载入视图文件
     * @param $file
     */
    public function view($file){
        include(__DIR__."/view/".$file.".php");
    }

    /**
     * 后台导入的菜单
     */
    public  static function admin_menu(){
        global $import_excel;

        add_submenu_page( 'tools.php', __( '导入Excel' ), __( '导入Excel' ), $import_excel->settings['access_level'], basename(__FILE__), array( &$import_excel, 'admin_page' ) );
    }

    /**
     * 头部css文件
     */
    public static function admin_head(){
        $ecsvi_url = plugins_url( '/css/import.css', __FILE__ );
        echo '<link type="text/css" rel="stylesheet" href="' . $ecsvi_url . '" />' . "\n";
    }
}

$GLOBALS['import_excel'] = new import_excel();

add_action( 'admin_menu', array("import_excel","admin_menu") );
add_action( 'admin_head',  array("import_excel","admin_head") );